﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace FYPHP
{
    public partial class CategoryManage : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["fyphp"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            SqlCommand cmdCat;
            SqlDataReader dtrCat;
            conn.Open();

            cmdCat = new SqlCommand("SELECT * FROM Category WHERE cat_status='publish' ORDER BY cat_name", conn);
            dtrCat = cmdCat.ExecuteReader();

            ItemList.DataSource = dtrCat;
            ItemList.DataBind();

            dtrCat.Close();
            conn.Close();
        }

        protected void ItemList_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "EditCategory")
            {
                int cid = Convert.ToInt32(e.CommandArgument.ToString());
                Redirect("CategoryEdit.aspx?id=" + cid);
            }

            else if (e.CommandName == "DeleteCategory")
            {
                int cid = Convert.ToInt32(e.CommandArgument.ToString());
                SqlCommand dltProduct;
                conn.Open();

                dltProduct = new SqlCommand("UPDATE Category SET cat_status='remove' WHERE cat_id=@id", conn);
                dltProduct.Parameters.AddWithValue("@id", cid);
                dltProduct.ExecuteNonQuery();

                MessageBox("Delete successfully!");
                Redirect("CategoryManage.aspx");
            }
        }

        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        private void Redirect(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language=\"javascript\">window.location='" + msg + "';</script>";
            Page.Controls.Add(lbl);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtCat.Text == "")
            {
                MessageBox("Please enter a category name!");
            }
            else
            {
                SqlCommand cmdAdd;
                conn.Open();

                cmdAdd = new SqlCommand("INSERT INTO Category VALUES(@name, 'publish')", conn);
                cmdAdd.Parameters.AddWithValue("@name", txtCat.Text);
                cmdAdd.ExecuteNonQuery();

                conn.Close();

                MessageBox("Successfully added!");
                Redirect("CategoryManage.aspx");
            }
        }
    }
}